<template>
  <view class="py-12">
    <BasicsForm @register="handleRegister" @on-schema-change="onSchemaChange">
      <template #formAdministrator>
        <view @click="showUniPopup(formAdministratorRef, 'formAdministrator')" class="simulationSelect">
          <text v-if="formAdministratorRef.length">
            {{ `已设置 ${formAdministratorRef.length} 个管理员` }}
          </text>
          <text v-else class="placeholder ov-1">选择管理员和你一起管理表单</text>
          <text class="ali-icon icon-xia fz-15"></text>
        </view>
      </template>
      <template #fillPeople>
        <template v-if="whoCanFillItInRef == ServiceFormFillingPermissionEnum.PartAdministrators">
          <view @click="showUniPopup(fillPeopleRef as number[], 'fillPeople')">
            <text v-if="fillPeopleRef.length">
              {{ `已选 ${fillPeopleRef.length} 人` }}
            </text>
            <text v-else>选择可填写人员</text>
          </view>
        </template>
        <template v-else>
          <view v-if="fillPeopleRef.length" class="disFlxAC">
            <view class="pr-10 fz-12">已选 {{ fillPeopleRef.length }}人</view>
            <TButton
              text="查看已选名单"
              custom-class="br-12 linh-22 fz-12"
              :custom-style="{ height: '48rpx', color: '#2878FF', border: 'solid 1px #2878FF' }"
              @click="toSelectedList"
            />
          </view>
          <view v-else @click="toSelectUser">选择可填写人员</view>
        </template>
      </template>
    </BasicsForm>
    <TButtonGroup :styles="{ backgroundColor: '#fff' }">
      <TButton
        class="gutter-btn"
        text="上一步"
        type="none"
        custom-class="borderBtn"
        @click.stop="emits('lastStep')"
      />
      <TButton class="gutter-btn" text="保存表单" type="primary" @click="emits('nextStep')" />
    </TButtonGroup>
  </view>
</template>

<script setup lang="ts">
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import { useForm } from '@/components/Form';
  import { navigateTo } from '@/router';
  import { ref, type PropType } from 'vue';
  import { serviceTicketFormPublishSet } from '@/api/serviceForm';
  import type { ServiceTicketFormTemplateDetailResult } from '@/api/serviceForm/types';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { MemberRoleEnum } from '@/enums/memberRoleEnum';
  import type { OnchangeArgument } from '@/components/Form/types';
  import { cloneDeep, isArray } from 'lodash-es';
  import {
    CanEndEnum,
    CanModifyEnum,
    FillInTheFrequencyLimitEnum,
    PermissionsTypeEnum,
    ServiceFormFillingPermissionEnum,
    ServiceFormStatusEnum,
  } from '@/enums/serviceFormEnum';
  import type { ServiceTicketFormPublishSetData } from '@/api/serviceForm/types';
  import { propTypes } from '@/utils/propTypes';
  import { useAppStore } from '@/store/modules/app';
  import type { PublicSelectUserList } from '@/router/types/modules';
  import { isString } from '@/utils/is';

  const systemInfo = uni.getWindowInfo();

  const emits = defineEmits(['showUniPopup', 'lastStep', 'nextStep']);

  const props = defineProps({
    details: Object as PropType<ServiceTicketFormTemplateDetailResult>,
    posterPath: propTypes.string,
  });

  const fillPeopleKeyMap: { [x: number]: { key: string; permissionsType: PermissionsTypeEnum } } = {
    [ServiceFormFillingPermissionEnum.PartMembers]: {
      key: 'memberId',
      permissionsType: PermissionsTypeEnum.Member,
    },
    [ServiceFormFillingPermissionEnum.PartAdministrators]: {
      key: 'sysUserId',
      permissionsType: PermissionsTypeEnum.Secretary,
    },
  };

  const [register, { validate, setFieldsValue }] = useForm({
    labelAlign: 'left',
    validateTrigger: 'submit',
    labelWidth: 120,
    schemas: [
      {
        label: '表单管理员',
        field: 'formAdministrator',
        component: 'Select',
        slot: 'formAdministrator',
        required: false,
      },
      {
        label: '谁能填写表单',
        field: 'whoCanFillItIn',
        component: 'Select',
        defaultValue: 0,
        isOnChange: true,
        componentProps: {
          localdata: [
            {
              text: `所有用户（不含管理员）可填写`,
              value: ServiceFormFillingPermissionEnum.Everyone,
            },
            {
              text: '所有用户（含管理员）可填写',
              value: ServiceFormFillingPermissionEnum.AllUsersIncludingAdministrato,
            },
            {
              text: `所有会员（不含管理员）可填写`,
              value: ServiceFormFillingPermissionEnum.AllMembers,
            },
            {
              text: '所有会员（含管理员）可填写',
              value: ServiceFormFillingPermissionEnum.AllMembersIncludingAdministrato,
            },
            {
              text: '部分会员可填写',
              value: ServiceFormFillingPermissionEnum.PartMembers,
            },
            {
              text: '所有管理员可填写',
              value: ServiceFormFillingPermissionEnum.AllAdministrators,
            },
            {
              text: '部分管理员可填写',
              value: ServiceFormFillingPermissionEnum.PartAdministrators,
            },
          ],
        },
      },
      {
        label: '可填写人员',
        field: 'fillPeople',
        component: 'Select',
        slot: 'fillPeople',
        required: true,
        ifShow: ({ model }) =>
          model.whoCanFillItIn === ServiceFormFillingPermissionEnum.PartMembers ||
          model.whoCanFillItIn === ServiceFormFillingPermissionEnum.PartAdministrators,
      },
      {
        label: '填写次数限制',
        field: 'fillTimesLimit',
        component: 'Select',
        defaultValue: 0,
        componentProps: {
          localdata: [
            {
              text: `不限`,
              value: FillInTheFrequencyLimitEnum.Unlimited,
            },
            {
              text: `限制每天填写次数`,
              value: FillInTheFrequencyLimitEnum.Daily,
            },
            {
              text: `限制每人填写次数`,
              value: FillInTheFrequencyLimitEnum.Personal,
            },
          ],
        },
      },
      {
        label: '可填写次数',
        field: 'fillTimes',
        component: 'InputNumber',
        defaultValue: 1,
        ifShow: ({ model }) => {
          return model.fillTimesLimit !== FillInTheFrequencyLimitEnum.Unlimited;
        },
        componentProps: {
          min: 1,
        },
      },
      {
        label: '限制结束填写时间',
        field: 'limitEndTime',
        component: 'Switch',
        labelWidth: systemInfo.windowWidth - 100,
        defaultValue: false,
      },
      {
        label: '选择时间',
        field: 'endTime',
        component: 'DateTimePicker',
        labelWidth: 110,
        required: true,
        ifShow: ({ model }) => {
          return model.limitEndTime;
        },
      },
      {
        label: '允许填写完成后修改答卷',
        field: 'allowModifyAnswer',
        component: 'Switch',
        labelWidth: systemInfo.windowWidth - 100,
        defaultValue: false,
      },
    ],
  });

  function handleRegister(e: any) {
    register(e);
    if (props.details) {
      const ticketManagerList =
        props.details.ticketManagerList?.map((item) => item.sysUserId) || [];
      const whoCanFillItIn = props.details.formPermissions;
      const res = fillPeopleKeyMap[whoCanFillItIn as number];
      if (res?.key) {
        const ticketPermissionsList =
          props.details.ticketPermissionsList?.map((item) => {
            const val = (item as any)[res.key];
            return whoCanFillItIn === ServiceFormFillingPermissionEnum.PartMembers
              ? val.toString()
              : val;
          }) || [];
        setFillPeopleVal(ticketPermissionsList);
      }
      setFormAdministratorRef(ticketManagerList);
      whoCanFillItInRef.value = whoCanFillItIn;
      setFieldsValue({
        whoCanFillItIn,
        fillTimesLimit: props.details.participationType,
        fillTimes: props.details.participationNumber || 1,
        limitEndTime: !!props.details.canEnd,
        endTime: props.details.endTime,
        allowModifyAnswer: !!props.details.canModify,
      });
    }
  }

  const whoCanFillItInRef = ref<number>();
  function onSchemaChange(e: OnchangeArgument) {
    if (e.field === 'whoCanFillItIn') {
      whoCanFillItInRef.value = e.val as number;
      fillPeopleRef.value = [];
    }
  }

  const fillPeopleRef = ref<PublicSelectUserList['selectedList']>([]);
  function setFillPeopleVal(list: PublicSelectUserList['selectedList']) {
    const val = cloneDeep(list);
    fillPeopleRef.value = val;
    setFieldsValue({
      fillPeople: val,
    });
  }
  const formAdministratorRef = ref<number[]>([]);
  function setFormAdministratorRef(list: number[]) {
    const val = cloneDeep(list);
    formAdministratorRef.value = val;
    setFieldsValue({
      formAdministrator: val,
    });
  }

  const tempSelectedType = ref<'fillPeople' | 'formAdministrator'>();
  function showUniPopup(list: number[], type: 'fillPeople' | 'formAdministrator') {
    tempSelectedType.value = type;
    emits('showUniPopup', list);
  }

  function toSelectUser() {
    navigateTo({
      name: 'publicSelectUserList',
      options: {
        type: 'checkbox',
        dataSource: 'memberList',
        initRoleIds: [MemberRoleEnum.PRINCIPAL],
        selectedList: fillPeopleRef.value,
        success: (val) => {
          fillPeopleRef.value = val;
          setFillPeopleVal(val);
        },
      },
    });
  }

  function toSelectedList() {
    navigateTo({
      name: 'publicSelectedUserList',
      options: {
        type: 'checkbox',
        dataSource: 'memberList',
        initRoleIds: [MemberRoleEnum.PRINCIPAL],
        selectedList: fillPeopleRef.value,
        success: (val) => {
          fillPeopleRef.value = val;
          setFillPeopleVal(val);
        },
      },
    });
  }

  defineExpose({
    submitSelected: (list: number[]) => {
      console.log(list);

      if (tempSelectedType.value === 'fillPeople') {
        setFillPeopleVal(list);
      }
      if (tempSelectedType.value === 'formAdministrator') {
        setFormAdministratorRef(list);
      }
      tempSelectedType.value = void 0;
    },
    submit: () => {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await validate();
          const whoCanFillItIn = res['whoCanFillItIn'] as ServiceFormFillingPermissionEnum;
          const params: ServiceTicketFormPublishSetData = {
            serviceTicketFormId: props.details?.id,
            participationType: res['fillTimesLimit'],
            canModify: res['allowModifyAnswer'] ? CanModifyEnum.Yes : CanModifyEnum.No,
            canEnd: res['limitEndTime'] ? CanEndEnum.Yes : CanEndEnum.No,
            status: ServiceFormStatusEnum.Down,
            endTime: res['endTime'],
            formPermissions: whoCanFillItIn,
            participationNumber: res['fillTimes'],
            ticketManagerList: [],
            ticketPermissionsList: [],
            img: props.posterPath,
          };

          if (res['formAdministrator']) {
            const formAdministrator = isString(res['formAdministrator'])
              ? res['formAdministrator'].split(',')
              : res['formAdministrator'];
            params.ticketManagerList = formAdministrator.map((v: number) => {
              return { sysUserId: v };
            });
          }

          if (res['fillPeople'] && Object.hasOwn(fillPeopleKeyMap, whoCanFillItIn)) {
            const fillPeople = isString(res['fillPeople'])
              ? res['fillPeople'].split(',')
              : res['fillPeople'];
            params.ticketPermissionsList = (isArray(fillPeople) ? fillPeople : []).map((v) => {
              const { key, permissionsType } = fillPeopleKeyMap[whoCanFillItIn];
              return {
                [key]: v,
                permissionsType: permissionsType,
              };
            });
          }

          await serviceTicketFormPublishSet(params);
          resolve(res);
        } catch (error) {
          reject();
        }
      });
    },
  });
</script>

<style lang="scss" scoped>
.simulationSelect{
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 72rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20rpx;
  font-size: 27rpx;
  color: #333;
  .placeholder{
    color: #999996;
  }
}
</style>
